﻿using System.Net.Sockets;
using System.Net;
using System.Text;
using System;

namespace UdpTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint remoteEndPointFrom = new IPEndPoint(IPAddress.Any, 0);
            string sendData = "5354415254000029000008651830718550742411281501074e4500150000010100003c241112160000000002c30000000057";
            var bufferSend = Enumerable.Range(0, sendData.Length / 2).Select(x => Convert.ToByte(sendData.Substring(x * 2, 2), 16)).ToArray();

            var destIp = "120.133.137.150";
            var destPort = "1705";

            int sendTotal = 0;
            int receiveTotal = 0;

            try
            {
                int receivePort = new Random().Next(10000, 20000);
                using UdpClient server = new UdpClient(receivePort);
                Console.WriteLine("服务器正在监听端口: " + receivePort);

                Task.Run(() =>
                {
                    while (true)
                    {
                        IPEndPoint remoteEndPointTo = new IPEndPoint(IPAddress.Parse(destIp), int.Parse(destPort));

                        Thread.Sleep(3000);
                        server.Send(bufferSend, bufferSend.Length, remoteEndPointTo);
                        sendTotal++;
                        Console.WriteLine($"{DateTime.Now}\t发送到：{destIp}:{destPort}\t发送总数：{sendTotal}\t内容：{sendData}");

                    }
                });

                while (true)
                {
                    byte[] buffer = server.Receive(ref remoteEndPointFrom);
                    string receiveData = BitConverter.ToString(buffer).Replace("-", "");
                    receiveTotal++;
                    Console.WriteLine($"{DateTime.Now}\t接收自：{remoteEndPointFrom}\t接收总数：{receiveTotal}\t内容：{receiveData}");
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
